<template>
  <div style="padding: 10px 0px">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="pay">收银</el-button>
      <el-button type="primary" @click="recharge">充值</el-button>
      <el-button type="primary" @click="exportExcelBill" >导出账单</el-button>
      <el-button type="primary" @click="exportExcelSales" >导出销售明细</el-button>
      <!--    日期范围选择-->
      <el-date-picker
        style="margin-left: 50px"
        v-model="dataValue"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      />
      <el-button type="primary" @click="inquire">账单查询</el-button>
    </div>
    <!--    账单table-->
    <el-table
      :data="tableData"
      style="width: 80%;margin-left: 10%"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="账单 ID:">
              <span>{{ props.row.bill.billId }}</span>
            </el-form-item>
            <el-form-item label="会员名称:">
              <span>{{ props.row.bill.memberName }}</span>
            </el-form-item>
            <el-form-item label="创建时间:">
              <span>{{ formatTimer(props.row.bill.gmtCreate) }}</span>
            </el-form-item>
            <el-form-item label="应收款:">
              <span>{{ props.row.bill.sumMoney }}</span>
            </el-form-item>
            <el-form-item label="实收款:">
              <span>{{ props.row.bill.realMoney }}</span>
            </el-form-item>
            <hr>
            <el-tag type="success">商品详情:</el-tag>
            <!--            商品详情-->
            <el-table
              :data="props.row.gooseBill"
              stripe
              style="width: 100%"
            >
              <el-table-column
                prop="gooseName"
                label="商品名称"
              />
              <el-table-column
                prop="standard"
                label="规格"
              />
              <el-table-column
                prop="num"
                label="数量"
              />
              <el-table-column
                prop="sellPrice"
                label="原价(元)"
              />
              <el-table-column
                prop="price"
                label="实价(元)"
              />
            </el-table>

          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        label="账单 ID"
        prop="bill.billId"
      />
      <el-table-column
        label="会员名称"
        prop="bill.memberName"
      />
      <el-table-column
        label="收款"
        prop="bill.realMoney"
      />
    </el-table>
  </div>
</template>

<script>

import { inquireBill } from '@/api/bill'
import { Message } from '_element-ui@2.13.2@element-ui'
import { parseTime } from '@/utils'

export default {
  name: 'Dashboard',
  data() {
    return {
      // 表格数据
      tableData: [],
      // 快捷选取时间
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      // 时间选择范围
      dataValue: [],
      // 账单数据
      bill: [],
      // 销售详情
      salesData: []
    }
  },
  methods: {
    // 封装时间转换
    formatTimer: function(value) {
      const date = new Date(value)
      const y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      // eslint-disable-next-line no-unused-vars
      let s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m
    },
    // 点击查询
    inquire() {
      if (this.dataValue.length !== 0) {
        const star = this.dataValue[0]
        const end = this.dataValue[1]
        new Promise((resolve, reject) => {
          inquireBill(star, end).then(response => {
            if (response.code === 20000) {
              Message({
                message: '查询成功!',
                type: 'success',
                duration: 3 * 1000
              })
            }
            this.tableData = []
            this.tableData = response.data
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      }
    },
    // 点击收银
    pay() {
      this.$router.push('/payment/memberPayment')
    },
    // 点击充值
    recharge() {
      this.$router.push('/recharge')
    },
    // 导出Excel 工具
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 导出账单
    exportExcelBill() {
      if (this.tableData.length > 0) {
        this.bill = [] // 清空数组,防止脏数据
        let i = 1 // 明细计数
        for (const b of this.tableData) {
          // 格式化时间
          b.bill.gmtCreate = this.formatTimer(b.bill.gmtCreate)
          this.bill.push(b.bill)
          for (const g of b.gooseBill) {
            // 删除不必项
            delete g.gmtCreate
            delete g.billId
            // 添加新元素用于计数
            g.index = i++
            // 加入数组
            this.bill.push(g)
          }
        }
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '账单 ID', '会员名称', '创建时间', '应收款', '实收款', '商品销售明细====>(序号)',
            '商品名称', '规格', '数量', '原价(元)', '实价(元)'
          ]
          const filterVal = [
            'billId', 'memberName', 'gmtCreate', 'sumMoney', 'realMoney', 'index',
            'gooseName', 'standard', 'num', 'sellPrice', 'price'
          ]
          const list = this.bill
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader, // 表头 必填
            data, // 具体数据 必填
            filename: this.dataValue[0] + '至' + this.dataValue[1] + '账单数据', // 非必填
            autoWidth: true, // 非必填
            bookType: 'xlsx' // 非必填
          })
        })
      }
    },
    // 导出销售明细
    exportExcelSales() {
      if (this.tableData.length > 0) {
        this.salesData = []
        for (const b of this.tableData) {
          for (const g of b.gooseBill) {
            this.salesData.push(g)
          }
        }
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '商品名称', '规格', '数量', '原价(元)', '实价(元)'
          ]
          const filterVal = [
            'gooseName', 'standard', 'num', 'sellPrice', 'price'
          ]
          const list = this.salesData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader, // 表头 必填
            data, // 具体数据 必填
            filename: this.dataValue[0] + '至' + this.dataValue[1] + '商品销售数据', // 非必填
            autoWidth: true, // 非必填
            bookType: 'xlsx' // 非必填
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
